package Reflection.Constructor;

import java.lang.reflect.Constructor;

/**
 * @author zxc
 * @date 2023/04/07 23:04
 **/

public class ConstructorDemo {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException {
        System.out.println("获取所有公共构造方法===========");
        method1();

        System.out.println("获取所有构造方法===========");
        method2();

        System.out.println("获取指定参数的单个公共构造方法对象===========");
        method3();

        System.out.println("获取指定参数的单个构造方法对象===========");
        method4();
    }

    private static void method4() throws ClassNotFoundException, NoSuchMethodException {
        // Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes) ：返回指定参数的单个构造方法对象
        Class clazz = Class.forName("Reflection.Constructor.Student");
        System.out.println("String+int的构造");
        Constructor constructor = clazz.getDeclaredConstructor(String.class,int.class);
        System.out.println(constructor);
        System.out.println("String的构造");

        constructor=clazz.getDeclaredConstructor(String.class);
        System.out.println(constructor);

    }

    private static void method3() throws ClassNotFoundException, NoSuchMethodException {
        // Constructor<T> getConstructor(Class<?>... parameterTypes)：返回指定参数的单个公共构造方法对象
        Class clazz = Class.forName("Reflection.Constructor.Student");
        //小括号中,一定要跟构造方法的形参保持一致.
        Constructor constructor1 = clazz.getConstructor();
        System.out.println(constructor1);

        Constructor constructor2 = clazz.getConstructor(String.class, int.class);
        System.out.println(constructor2);

        // 因为Student类中,没有只有一个int的构造,所以这里会报错
        // 由于所获取的构造方法是private的，使用getConstructor方法是获取不到该私有构造方法的;
        Constructor constructor3 = clazz.getConstructor(int.class);
        System.out.println(constructor3);
    }

    private static void method2() throws ClassNotFoundException {
        // Constructor<?>[] getDeclaredConstructors() ：返回所有构造方法对象的数组
        Class clazz = Class.forName("Reflection.Constructor.Student");
        Constructor[] constructors = clazz.getDeclaredConstructors();
        for (Constructor constructor : constructors) {
            System.out.println(constructor);
        }
    }
    // 获取当前Class对象所对应类的所有公共构造方法;
    private static void method1() throws ClassNotFoundException {
        // Constructor<?>[] getConstructors( )：返回所有公共构造方法对象的数组
        Class clazz = Class.forName("Reflection.Constructor.Student");
        Constructor[] constructors = clazz.getConstructors();
        for (Constructor constructor : constructors) {
            System.out.println(constructor);
        }
    }
}

